<script setup lang="ts">
import { IllnessTime } from '@/enums'
import { uploaImg } from '@/services/consult'
import { useStore } from '@/stores'
import type { Image, PartialConsult } from '@/types/consult'
import { showConfirmDialog, showToast } from 'vant'
import type {
  UploaderAfterRead,
  UploaderFileListItem
} from 'vant/lib/uploader/types'
import { computed } from 'vue'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { flagOptions, timeOptions } from '@/services/constants'
const { consult } = useStore()
const form = ref<PartialConsult>({
  illnessDesc: '', // 病情描述
  illnessTime: undefined, // 患病周期
  consultFlag: undefined, // 是否就诊过
  pictures: [] // 患病图片信息
})
const fileList = ref<Image[]>([]) // 存储了临时路径的数组
// 文件读取成功后触发的函数
const afterRead: UploaderAfterRead = async (obj) => {
  if (Array.isArray(obj)) return // 禁止多选
  if (!obj.file) return // 没选
  try {
    obj.status = 'uploading'
    obj.message = '上传中...'
    const res = await uploaImg(obj.file)
    // 上传状态
    // 将结果追加到form.pictures中
    form.value.pictures?.push(res.data)
    obj.status = 'done'
    // console.log(obj.url)
    // obj.id = res.data.id 找一个共同点 查找数据  id字段会报类型的问题
    obj.url = res.data.id // 借助url属性 存储一下这个id  方便后面删除的时候找字段对比
  } catch {
    obj.status = 'failed'
    obj.message = '上传失败'
  }
}
// 删除图片 同步 pictures
const delImg = (obj: UploaderFileListItem) => {
  // console.log(obj.url) // 这个url其实就是记录的id
  // 拿着id去form.pictures中查找那一项过滤掉
  form.value.pictures = form.value.pictures?.filter(
    (item) => item.id !== obj.url
  )
}
const disabled = computed(() => {
  return (
    !form.value.illnessDesc?.length ||
    form.value.illnessTime === undefined ||
    form.value.consultFlag === undefined
  )
})

const router = useRouter()
// 提交
const next = () => {
  // 预校验
  if (!form.value.illnessDesc?.length) return showToast('请填写病情描述')
  if (form.value.illnessTime === undefined) return showToast('请选择患病时长')
  if (form.value.consultFlag === undefined) return showToast('请选择是否就诊过')
  // 2. 将四个字段存储到仓库中
  consult.setIllnessInfo(form.value)
  // 3.跳转
  router.push('/user/patient?isChange=1') // isChange只是一个区分的标识, 只是为了区分直接进入患者列表 病情咨询展示患者列表
}

// 回显表单数据
const showForm = () => {
  // 回显数据有一个前提 仓库模块中存储的有我们之前填写的信息
  if (consult.consult.illnessDesc) {
    showConfirmDialog({
      title: '温馨提示',
      message: '是否恢复您之前填写的病情信息呢?',
      closeOnPopstate: false // 是否在页面回退时自动关闭
    })
      .then(() => {
        // 点击确认回显数据
        const { illnessDesc, illnessTime, consultFlag, pictures } =
          consult.consult
        form.value = { illnessDesc, illnessTime, consultFlag, pictures }
        // 单独处理图片 将pictures交给 fileList
        fileList.value = pictures || []
      })
      .catch(() => {
        // on cancel
      })
  }
}
showForm()
</script>

<template>
  <div class="consult-illness-page">
    <cp-nav-bar title="图文问诊" />
    <!-- 医生提示 -->
    <div class="illness-tip van-hairline--bottom">
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <div class="info">
        <p class="tit">在线医生</p>
        <p class="tip">
          请描述你的疾病或症状、是否用药、就诊经历，需要我听过什么样的帮助
        </p>
        <p class="safe">
          <cp-icon name="consult-safe" /><span>内容仅医生可见</span>
        </p>
      </div>
    </div>
    <!-- 收集信息 -->
    <div class="illness-form">
      <van-field
        type="textarea"
        rows="3"
        placeholder="请详细描述您的病情，病情描述不能为空"
        v-model.trim="form.illnessDesc"
      ></van-field>
      <div class="item">
        <p>本次患病多久了？</p>
        <cp-radio-btn
          :options="timeOptions"
          v-model="form.illnessTime"
        ></cp-radio-btn>
      </div>
      <div class="item">
        <p>此次病情是否去医院就诊过？</p>
        <cp-radio-btn
          :options="flagOptions"
          v-model="form.consultFlag"
        ></cp-radio-btn>
      </div>
      <!-- 上传组件 -->
      <div class="illness-img">
        <!-- upload-icon 上传组件图标 
             upload-text	上传区域文字提示
             max-count	文件上传数量限制
             max-size	文件大小限制，单位为字节
             preview-size 预览图片尺寸大小
             v-model 文件列表 是一个数组
        -->
        <van-uploader
          v-model="fileList"
          upload-icon="photo-o"
          upload-text="上传图片"
          max-count="9"
          max-size="5 * 1024 * 1024"
          preview-size="107"
          :after-read="afterRead"
          @delete="delImg"
        ></van-uploader>
        <p class="tip" v-if="!fileList.length">
          上传内容仅医生可见,最多9张图,最大5MB
        </p>
      </div>
      <!-- 提交按钮-->
      <van-button :class="{ disabled }" @click="next" type="primary" block round
        >下一步</van-button
      >
    </div>
  </div>
</template>

<style lang="scss" scoped>
.van-button {
  font-size: 16px;
  margin-bottom: 30px;
  &.disabled {
    opacity: 1;
    background: #fafafa;
    color: #d9dbde;
    border: #fafafa;
  }
}

.illness-img {
  padding-top: 16px;
  margin-bottom: 40px;
  display: flex;
  align-items: center;
  .tip {
    font-size: 12px;
    color: var(--cp-tip);
  }
  ::v-deep() {
    .van-uploader {
      &__preview {
        &-delete {
          left: -6px;
          top: -6px;
          border-radius: 50%;
          background-color: var(--cp-primary);
          width: 20px;
          height: 20px;
          &-icon {
            transform: scale(0.9) translate(-22%, 22%);
          }
        }
        &-image {
          border-radius: 8px;
          overflow: hidden;
        }
      }
      &__upload {
        border-radius: 8px;
      }
      &__upload-icon {
        color: var(--cp-text3);
      }
    }
  }
}

.consult-illness-page {
  padding-top: 46px;
}
.illness-tip {
  display: flex;
  padding: 15px;
  .img {
    width: 52px;
    height: 52px;
    border-radius: 4px;
    overflow: hidden;
    margin-top: 10px;
  }
  .info {
    flex: 1;
    padding-left: 12px;
    .tit {
      font-size: 16px;
      margin-bottom: 5px;
    }
    .tip {
      padding: 12px;
      background: var(--cp-bg);
      color: var(--cp-text3);
      font-size: 13px;
      margin-bottom: 10px;
    }
    .safe {
      font-size: 10px;
      color: var(--cp-text3);
      display: flex;
      align-items: center;
      .cp-icon {
        font-size: 12px;
        margin-right: 2px;
      }
    }
  }
}
.illness-form {
  padding: 15px;
  .van-field {
    padding: 0;
    &::after {
      border-bottom: none;
    }
  }
  .item {
    > p {
      color: var(--cp-text3);
      padding: 15px 0;
    }
  }
}
</style>
